/*
 * UserButton.cpp
 *
 *  Created on: 30.11.2012
 *      Author: Michael
 */

#include "UserButton.h"

#include "rodos.h"

#include "stm32f4xx_misc.h"
#include "stm32f4xx_syscfg.h"
#include "stm32f4xx.h"

//class SigTermHandler :  public Subscriber {
//public:
//        SigTermHandler() : Subscriber(interruptSigterm, "simplesub") { }
//        void putFromInterrupt(const long topicId, const void* any, int len) {
//		xprintf("external Event at %3.9f datalen %d\n",  SECONDS_NOW(), len);
//        }
//} sigTermHandler;

UserButton::UserButton() {
	// TODO Auto-generated constructor stub
	initButton();
}

UserButton::~UserButton() {
	// TODO Auto-generated destructor stub
}

void UserButton::initButton() {
	GPIO_InitTypeDef GPIO_InitStructure;
	EXTI_InitTypeDef EXTI_InitStructure;
	NVIC_InitTypeDef NVIC_InitStructure;

	/* Enable the BUTTON Clock */
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);

	/* Configure Button pin as input */
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
	GPIO_Init(GPIOA, &GPIO_InitStructure);

	/* Connect Button EXTI Line to Button GPIO Pin */
	SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOA,
			EXTI_PinSource0);

	/* Configure Button EXTI line */
	EXTI_InitStructure.EXTI_Line = EXTI_Line0;
	EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
	EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
	EXTI_InitStructure.EXTI_LineCmd = ENABLE;
	EXTI_Init(&EXTI_InitStructure);

	/* Enable and set Button EXTI Interrupt to the lowest priority */
	NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x0F;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x0F;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;

	NVIC_Init(&NVIC_InitStructure);
}


uint32_t UserButton::getState()
{
  return GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0);
}
